/**********************************************************************
Compile : gcc -O3 -o alignment alignment.c optimize_i.c -lm
Usage : ./alignment 11 12 Yeast.txt Yeast.txt
**********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

extern int select_matrix (int N, int matrix[N][N], int order[N]);

void print_help ()
{
	printf ("Usage         : ./alignment N L templatefile inputfile\n");
	printf ("                (./alignment 11 12 Yeast.txt Yeast.txt)\n");
	printf ("N             : number of the nodes\n");
	printf ("L             : number of the steps\n");
}

void score_matrix (int N, int L, int pathway1[L][N], int pathway2[L][N], int matrix[N][N])
{
	int i, j, k;

	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			matrix[i][j] = 0;
			for (k = 0; k < L; k++)
			{
				matrix[i][j] += (pathway2[k][i] - pathway1[k][j]) * (pathway2[k][i] - pathway1[k][j]);
			}
		}
	}
}

void alignment (int N, int L, int pathway1[L][N], int pathway2[L][N])
{
	int i, j, score;
	int order[N], matrix[N][N];

	score_matrix (N, L, pathway1, pathway2, matrix);
	
	score = select_matrix (N, matrix, order);

	printf ("c Similarity score : %d\n", score);

	for (i = 0; i < L; i++)
	{
		for (j = 0; j < N; j++)
		{
			printf ("%d ", pathway2[i][order[j]]);
		}
		printf ("\n");
	}
}

int main (int argc, char *argv[])
{
	FILE *fp;
	char buf[256];
	int N, L;
	int i, j;

	if (argc == 1)
	{
		print_help ();
		exit (0);
	}

	N = atoi (argv[1]);
	L = atoi (argv[2]);

	int pathway1[L][N], pathway2[L][N];

	fp = fopen (argv[3], "r");
	fgets (buf, 256, fp);
	for (i = 0; i < L; i++)
	{
		for (j = 0; j < N; j++)
		{
			fscanf (fp, "%d", &(pathway1[i][j]));
		}
		fgets (buf, 256, fp);
	}
	fclose (fp);

	fp = fopen (argv[4], "r");
	while (fgets (buf, 256, fp))
	{
		printf ("%s", buf);
		for (i = 0; i < L; i++)
		{
			for (j = 0; j < N; j++)
			{
				fscanf (fp, "%d", &(pathway2[i][j]));
			}
			fgets (buf, 256, fp);
		}

		alignment (N, L, pathway1, pathway2);
	}
	fclose (fp);

	exit (0);
}
